/* jquery.imagefit 
 *
 * Version 0.2 by Oliver Boermans <http://www.ollicle.com/eg/jquery/imagefit/>
 *
 * Extends jQuery <http://jquery.com>
 *
 */
/*PIPAHR modification to support flexible max-width and load event */
(function($) {
   $.fn.imagefit = function(options) {
      var fit = {
         all : function(imgs){
            imgs.each(function(){
               fit.one(this);
               })
            },
         one : function(img){
            $(img)
               .width('100%').each(function()
               {
                  $(this).height(Math.round(
                     $(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
                  );
               })
            }
      };
      
      var container = options.container ? options.container : "#background"; 
      var maxwidth = parseInt($(container).css('max-width'));
      maxwidth = options.maxwidth ? options.maxwidth : maxwidth; 
      this.each(function(){
            var container = this;
            
            // store list of contained images (excluding those in tables)
            var imgs = $('img', container); //.not($("table img"));
            
            // store initial dimensions on each image 
            imgs.each(function(){
               $(this).one("load", function() {
                  // increase maxwith of body to hold the size of image 
                  if($(this).width() >= maxwidth)
                     $(container).css('max-width', (options.maxwidth ? maxwidth : "90%"));

                  var mx = $(this).width() > maxwidth ? maxwidth : $(this).width();
                  $(this).attr('startwidth', $(this).width())
                     .attr('startheight', $(this).height())
                     .css('max-width', mx+"px");
            
                  fit.one(this);
               }).each(function() {
                  /* if load from browser cache, we have complete property */
                  if(this.complete) $(this).load();
               })
            });
            // Re-adjust when window width is changed
            $(window).bind('resize', function(){
               fit.all(imgs);
            });
         });
      return this;
   };
})(jQuery);
